using System;
using System.Data;
//using System.Data.SQL;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using  System.Text.RegularExpressions ;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
namespace CStock
{
	/// <summary>
	/// Summary description for WebQuotes.
	/// </summary>
    public class YahooFeedSockets : WebQuotes
	{

        public YahooFeedSockets()
		{
			
		}
        /// <summary>
        /// GetLastIntradayQuote
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public static IQuoteWeb GetLastIntradayQuote(IDataItem di)
        {
            return GetYahoo_Intraday(di.Symbol, di.ID);

        }
        /// <summary>
        /// GetYahoo_Intraday
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
     
        /// <summary>
        /// GetYahoo_Intraday
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public static IQuoteWeb GetYahoo_Intraday(string symbol, string shareID)
        {
            bool bReadQuotePageFromDisk = false;
            bool bWriteQuotePageToDisk = true;

            IQuoteWeb quote = new QuoteWeb();

            DateTime dt = DateTime.Today;
            string year, month, day;//, high = "-", low  = "-", cassa = "-", wknv;
            year = dt.Year.ToString();
            month = dt.Month.ToString();
            day = dt.Day.ToString();
            string url_server, port, uri, retPage;
            
            Regex regex;
            //string retPage;
            url_server = string.Empty;
            port = string.Empty;

            RegExStructuresYahooRealtime regExStruct = new RegExStructuresYahooRealtime();


            string shareSearch = regExStruct.URL + symbol;


            SocketDownload.ExtractInternetParameters(shareSearch, out url_server, out port, out uri);
            quote.DATE = System.DateTime.Now;


            retPage = SocketDownload.GetQuote(url_server, port, uri, "", bWriteQuotePageToDisk, shareID, shareID);

            //-----------------------------------
            //testing
            if (bReadQuotePageFromDisk)
            {
                TextReader reader = new StreamReader(shareID + " - " + ".txt");
                char[] buf = new char[1000000];
                reader.Read(buf, 0, 1000000);
                retPage = new String(buf);
            }
            //-----------------------------------

            regex = null;
            try
            {
                regex = new Regex(@regExStruct.Quote);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error : " + ex.Message);
            }
                string time = string.Empty;
            if (regex.IsMatch(retPage))
            {
                time = regex.Match(retPage).Result("${1}");
            }
            else
            {
                time = "0:00";
               
            }
			
            string quoteResult = string.Empty;
            

            //			}
            return quote;

        }

        private static string GetYahooPage_Indexes(IPortfolio portf, out RegExStructuresYahooIndexData regExStruct)
        {
            string url_server, port, uri, retPage;
            url_server = string.Empty;
            port = string.Empty;
            regExStruct = new RegExStructuresYahooIndexData();
            string indexSearch = portf.URL_Overview;

            SocketDownload.ExtractInternetParameters(indexSearch, out url_server, out port, out uri);
            retPage = SocketDownload.GetQuote(url_server, port, uri, "");

            return retPage;

        }
        public static bool GetYahoo_ListOfGermanIndexes(IPortfolio portf, bool bTakeURLFromPortfolio)
        {
            try
            {
                //delete portfolio first!!

                RegExStructuresYahooIndexData regExStruct = null;
                string retPage = GetYahooPage_Indexes(portf, out regExStruct);

                MatchCollection matchesBlocks = Regex.Matches(retPage, @regExStruct.TableBlock);
                for (int i = 0; i < matchesBlocks.Count; i++)
                {
                    //adds also data to portfolio
                    InterpretMatches(i, regExStruct, matchesBlocks, portf);
                }

                return true;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error gettint overview list of stocks " + ex.Message);
                return false;
            }

        }
        private static string GetInternetPage_DE(IPortfolio portf, string url, bool bTakeURLFromPortfolio)
        {
            string url_server, port, uri, retPage;

            url_server = string.Empty;
            port = string.Empty;

            string indexSearch = url + portf.Symbol;
            if (bTakeURLFromPortfolio)
            {
                indexSearch = portf.URL_Overview;
            }
            SocketDownload.ExtractInternetParameters(indexSearch, out url_server, out port, out uri);




            retPage = SocketDownload.GetQuote(url_server, port, uri, "");
            return retPage;

        }
        public static bool GetYahoo_ListOfStocks_UK(string exchangeID)
        {


            string url_server, port, uri, retPage;
            url_server = string.Empty;
            port = string.Empty;

            RegExStructuresYahooStockSymbols_UK regExStruct = new RegExStructuresYahooStockSymbols_UK();


            string indexSearch = regExStruct.URL + exchangeID;


            SocketDownload.ExtractInternetParameters(indexSearch, out url_server, out port, out uri);

            IList<string> strNames = new List<string>();
            IList<string> strSymbols = new List<string>();

            retPage = SocketDownload.GetQuote(url_server, port, uri, "");

            MatchCollection matchesStockLines = Regex.Matches(retPage, @regExStruct.StockLine);
            for (int i = 0; i < matchesStockLines.Count; i++)
            {
                string symbol = string.Empty;
                string name = string.Empty;

                Match m = matchesStockLines[i];
                string strStockLine = m.Result("${1}");
                Regex regexSymbol = new Regex(@regExStruct.Symbol);
                if (!regexSymbol.IsMatch(strStockLine))
                {
                    Debug.Assert(false, "Symbol not found for line " + strStockLine);
                }
                else
                {
                    symbol = regexSymbol.Match(strStockLine).Result("${1}");

                    Regex regexName = new Regex(@regExStruct.Name);
                    if (!regexName.IsMatch(strStockLine))
                    {
                        regexName = new Regex(@regExStruct.NameCheck);
                        if (!regexName.IsMatch(strStockLine))
                        {
                            Debug.Assert(false, "Name not found for symbol " + exchangeID + "; share: " + symbol);

                        }
                        else
                        {
                            name = regexName.Match(strStockLine).Result("${1}");
                        }
                    }
                    else
                    {
                        name = regexName.Match(strStockLine).Result("${1}");
                    }
                }
                strNames.Add(name);
                strSymbols.Add(symbol);
                //MatchCollection matchesName = Regex.Matches(strStockLine, @regExStruct.StockLine);
            }

            return true;


            //			}


        }
        /// GetConsorsQuote_Perstring
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public static IQuoteWeb GetConsorsQuote_Perstring(string wknSearch, string shareName, string shareID)
        {
            //neu: https://www.cortalconsors.de/euroWebDe/-?%24event=search&pattern=723610&%24part=msg.404.index.security-search

            //GetQuote_Perstring (dc.ID, dc.Name, dc.ID )
            bool bReadQuotePageFromDisk = false;
            bool bWriteQuotePageToDisk = true;



            IQuoteWeb quote = new QuoteWeb();

            DateTime dt = DateTime.Today;
            string year, month, day;//, high = "-", low  = "-", cassa = "-", wknv;
            year = dt.Year.ToString();
            month = dt.Month.ToString();
            day = dt.Day.ToString();
            //string server = "consors";

            string url_server, port, uri, retPage;
            //string s1 ="No match", s2 = "", s3 = "", s4 = "";


            Regex regex;
            url_server = "https://www.cortalconsors.de";
            port = "80";
            //https://www.cortalconsors.de/euroWebDe/-?$part=financeinfosHome.Desks.searchresult.content.searchresult.searchSTO&$event=snapshot&id_name=ISIN&id=DE0007236101&exchange=PNK

            RegExStructuresConsors regExStruct = new RegExStructuresConsors(0);


            string shareSearch = regExStruct.URL + wknSearch;


            SocketDownload.ExtractInternetParameters(shareSearch, out url_server, out port, out uri);

            quote.DATE = System.DateTime.Now;


            retPage = SocketDownload.GetQuote(url_server, port, uri, "", bWriteQuotePageToDisk, shareName, shareID);

            //-----------------------------------
            //testing
            if (bReadQuotePageFromDisk)
            {
                TextReader reader = new StreamReader(shareName + " - " + shareID + ".txt");
                char[] buf = new char[1000000];
                reader.Read(buf, 0, 1000000);
                retPage = new String(buf);
            }
            //-----------------------------------


            string quoteResult = string.Empty;
            string quoteSearch = regExStruct.Quote;
            regex = new Regex(@quoteSearch);

            MatchCollection matches = Regex.Matches(retPage, quoteSearch);
            try
            {
                Match m = matches[0];
                quoteResult = m.ToString();

                if (regex.IsMatch(retPage))
                {
                    quoteResult = regex.Match(retPage).Result("${1}");
                }
                else
                {
                    quoteResult = "0";
                    //return quote;
                }
                quote.LastPrice = System.Convert.ToDouble(quoteResult);
            }
            catch
            {
                //System.Diagnostics.Debug.Assert(false,"No Quote Information for " + shareID );
                //search for reduced
                try
                {
                    quoteSearch = regExStruct.QuoteReduced;
                    regex = new Regex(@quoteSearch);
                    quoteResult = regex.Match(retPage).Result("${1}");
                    quote.LastPrice = System.Convert.ToDouble(quoteResult);
                }
                catch
                {
                    //do nothing
                }
            }





            //regex = new Regex (@regexp, "i");
            regex = new Regex(@regExStruct.Time);
            string time = string.Empty;
            if (regex.IsMatch(retPage))
            {
                time = regex.Match(retPage).Result("${1}");
            }
            else
            {
                time = "0:00";
                //System.Diagnostics.Debug.Assert(false,"No Time Information for " +  shareID );
                //return quote;
            }

            quote.TimeLastTransaction = System.Convert.ToDateTime(time);

            regex = new Regex(@regExStruct.Volume);
            string volume = string.Empty;
            if (regex.IsMatch(retPage))
            {
                volume = regex.Match(retPage).Result("${1}");
            }
            else
            {
                //System.Diagnostics.Debug.Assert(false,"No Volume Information for " +  shareID );
                volume = "0";
                //return quote;
            }

            try
            {

                //quote.Volume = Convert.ToInt64(volume);
            }
            catch (Exception exc)
            {
                //Do nothing
                Debug.WriteLine("Volume is not in correct format " + exc.Message);
            }


            regex = new Regex(@regExStruct.VolumeTotal);
            string volumeTotal = string.Empty;
            if (regex.IsMatch(retPage))
            {
                volumeTotal = regex.Match(retPage).Result("${1}");

            }
            else
            {
                volumeTotal = "0";
                //System.Diagnostics.Debug.Assert(false,"No VolumeTotal Information for " +  shareID );
                //return quote;
            }
            try
            {
                quote.VolumeTotal = Convert.ToInt64(volumeTotal);
            }
            catch (Exception exc)
            {
                //Do nothing
                Debug.WriteLine("Volume is not in correct format " + exc.Message);
            }
            //quote.VolumeTotal = volumeTotal;




            regex = new Regex(@regExStruct.Bid);
            string bid = string.Empty;
            string bidQty = string.Empty;

            if (regex.IsMatch(retPage))
            {
                bid = regex.Match(retPage).Result("${1}");
                bidQty = regex.Match(retPage).Result("${2}");

            }
            else
            {
                bid = "0";
                bidQty = "0";
                //System.Diagnostics.Debug.Assert(false,"No Bid Information for " +  shareID );
                //return quote;
            }
            quote.Bid = System.Convert.ToDouble(bid);
            quote.BidSize = Convert.ToInt32(bidQty);

            regex = new Regex(@regExStruct.Ask);
            string ask = string.Empty;
            string askQty = string.Empty;

            if (regex.IsMatch(retPage))
            {
                ask = regex.Match(retPage).Result("${1}");
                askQty = regex.Match(retPage).Result("${2}");

            }
            else
            {
                ask = "0";
                askQty = "0";

                //System.Diagnostics.Debug.Assert(false,"No Ask Information for " +  shareID );
                //return quote;
            }
            try
            {
                quote.Ask = System.Convert.ToDouble(ask);
            }
            catch (Exception exc)
            {
                //Do nothing
                Debug.WriteLine("Ask is not in correct format " + exc.Message);
            }
            try
            {
                quote.AskSize = Convert.ToInt32(askQty);
            }
            catch (Exception exc)
            {
                //Do nothing
                Debug.WriteLine("AskSize is not in correct format " + exc.Message);
            }







            try
            {
                //mySQLCommand.ExecuteNonQuery();	// remove record that may have been entered previously.
            }
            catch (Exception e)
            {
                string str = "Error on execute sql commmand: " + " Errormessage: " + e.Message;

            }

            //			}
            return quote;

        }

        /// <summary>
        /// GetQuotes
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public static IQuoteWeb GetQuotes(IDataClass dc)
        {
            return GetConsorsQuote_Perstring(dc.ID, dc.Name, dc.ID);

        }
        /// <summary>
        /// GetQuotes
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public static IQuoteWeb GetQuotes(string wkn, string name, string id)
        {
            return GetConsorsQuote_Perstring(wkn, name, id);

        }

        public static IQuoteWeb GetYahoo_RealtimeECN(IDataItem di, string url)
        {
            string symbol = di.Symbol;
            string shareID = di.ID;


            //url is: http://finance.yahoo.com/q/ecn?s=  
            //+ symbol like "DB"

            bool bWriteQuotePageToDisk = true;

            IQuoteWeb quote = new QuoteWeb();
            DateTime dt = DateTime.Today;
            string url_server, port, uri, retPage;


            //string retPage;
            url_server = string.Empty;
            port = string.Empty;

            RegExStructuresYahooREaltimeECN regExStruct = new RegExStructuresYahooREaltimeECN();

            string shareSearch = url + symbol;
            SocketDownload.ExtractInternetParameters(shareSearch, out url_server, out port, out uri);


            quote.DATE = new System.DateTime(1900, 1, 1);


            retPage = SocketDownload.GetQuote(url_server, port, uri, "", bWriteQuotePageToDisk, shareID, shareID);




            string time = string.Empty;
            Regex regex = null;
            try
            {
                //string strToSearch = @regExStruct.LastTrade + symbol.ToLower() + @regExStruct.Suffix;
                //regex = new Regex(@regExStruct.LastTrade + symbol.ToLower() + @regExStruct.Suffix);
                regex = new Regex(@regExStruct.LastTrade);

                if (regex.IsMatch(retPage))
                {
                    string strFound = regex.Match(retPage).Result("${1}");
                    double f = Convert.ToDouble(strFound, CUtil.Conversions.CultureAmerican);
                    quote.CLOSEc = f;
                }
                MatchCollection matches = Regex.Matches(retPage, @regExStruct.Bid);
                for (int i = 0; i < matches.Count; i++)
                {
                    Match m = matches[i];
                    string strFound = m.Result("${1}");
                    double f = Convert.ToDouble(strFound, CUtil.Conversions.CultureAmerican);
                    if (i == 0)
                        quote.Bid = f;
                    if (i == 1)
                        quote.Ask = f;
                }

                regex = new Regex(@regExStruct.Tradetime);
                if (regex.IsMatch(retPage))
                {
                    string tradeTime = regex.Match(retPage).Result("${1}");
                    tradeTime = tradeTime.Remove(tradeTime.Length - 3, 3);
                    DateTime f = Convert.ToDateTime(tradeTime, CUtil.Conversions.CultureAmerican);
                    quote.TIME_OfDay = f;
                }

            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error getting intraday data for " + shareID + "; " + ex.Message);
            }
            if (quote.TIME_OfDay.Year != 1)
            {
                //if(di.DataClass.QuotesI
            }
            string quoteResult = string.Empty;


            //			}
            return quote;

        }
        public static bool GetYahoo_ListOfStocks_DE(IPortfolio portf, bool bTakeURLFromPortfolio)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Getting data for portfolio " + portf.ID);
                RegExStructuresYahooStockSymbols_DE regExStruct = new RegExStructuresYahooStockSymbols_DE();
                string retPage = GetInternetPage_DE(portf, regExStruct.URL, bTakeURLFromPortfolio);


                IList<string> strNames = new List<string>();
                IList<string> strSymbols = new List<string>();


                //AdjustNameCollections(retPage, regExStruct, indexSearch);
                MatchCollection matchesStockLines = Regex.Matches(retPage, @regExStruct.StockLine);
                for (int i = 0; i < matchesStockLines.Count; i++)
                {
                    string symbol = string.Empty;
                    string name = string.Empty;
                    Match m = matchesStockLines[i];
                    GetNameAndSymbol(m, regExStruct, out name, out symbol);

                    strNames.Add(name);
                    strSymbols.Add(symbol);

                }

                CreatePortfolioEntries(portf, strNames, strSymbols);


                return true;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error gettint overview list of stocks " + ex.Message);
                return false;
            }

        }


        private static bool CreatePortfolioEntries(IPortfolio portf, IList<string> strNames, IList<string> strSymbols)
        {
            for (int i = 0; i < strNames.Count; i++)
            {
                IDataItem di = new DataItem();
                di.Parent = portf;
                di.DataClass = new DataClassDaily();
                di.DataClass.ID = strNames[i];
                di.DataClass.Parent = di;
                di.Symbol = strSymbols[i];
                di.ID = strNames[i];
                di.Serialize();
                portf.DataItems.Items.Add(di);

            }
            return true;
        }
       
     
	}
}
